package part18;

import java.io.BufferedReader;
import java.io.InputStreamReader;

/**
 * @author wcj
 * @Date 2021/6/3 19:47
 * @Version 1.0
 */
public class Part1819 {

    /**
     * 进程控制，即执行控制台输入的命令创建进行执行
     *
     * @param command
     */
    public static void command(String command) {
        boolean err = false;
        try {
            Process process = new ProcessBuilder(command.split(" ")).start();
            BufferedReader results = new BufferedReader(new InputStreamReader(process.getInputStream()));
            String s;
            while ((s = results.readLine()) != null) {
                System.out.println(s);
            }
            BufferedReader errors = new BufferedReader(new InputStreamReader(process.getErrorStream()));
            while ((s = errors.readLine()) != null) {
                System.err.println(s);
                err = true;
            }
        } catch (Exception e) {
            if (!command.startsWith("CMD /C")) {
                command("CMD /C " + command);
            } else {
                throw new RuntimeException(e);
            }
        }
        if (err) {
            throw new OSExecuteException("Errors executing " + command);
        }
    }

    public static void main(String[] args) {
        command("javap OSExecuteDemo");
    }
}

class OSExecuteException extends RuntimeException {
    public OSExecuteException(String why) {
        super(why);
    }
}
